package com.atfzr.completablFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author 望夜
 * @date 2023/8/15---9:34
 * @SuppressWarnings({"all"})
 */
public class CompletableFutureAPI2Demo {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(()->{
            //暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("111");
            return 1;
        }).handle((f,e) -> { //  thenApply()和 handle()
            int i = 10 / 0; //经典bug
            System.out.println("222");
            return f + 2;
        }).handle((f,e) -> {
            System.out.println("333");
            return f+3;
        }).whenComplete((v,e) ->{
            if(e == null){
                System.out.println("----计算结果: " + v);
            }
        }).exceptionally(e ->{ //exceptionally() 相当于try-catch里的finally
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "----主线程先去忙其它任务");

    }
}
